#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/13  12:52
# @Author: 余浪人
# @email: yulangren520@gmail.com
import os
from flask import request, jsonify
from flask_login import login_required
from apps.control import sys_bp
from apps import get_sys_url
from apps.lib.public import get_uuid16, get_date_str
from qiniu import Auth, put_data
from apps.models.system_model import TL_Save_Model


def qiNiu_upload(fileName: str, file_data):
    try:
        save_obj = TL_Save_Model.query.first()
        if save_obj.save_classification == 3:  # 七牛存储
            q = Auth(save_obj.access_key, save_obj.secret_key)
            _path = save_obj.save_path[1:] if save_obj.save_path[0] == '/' else save_obj.save_path
            _path = _path if _path[-1] == '/' else _path + '/'
            fileName_ = os.path.join(_path, fileName)
            token = q.upload_token(save_obj.bucket_name, fileName_, 3600)
            ret, info = put_data(token, fileName_, file_data)
            assert ret['key'] == fileName_
            base = save_obj.bucket_domain if save_obj.bucket_domain[-1] == '/' else save_obj.bucket_domain + '/'
            return base + fileName_
        elif save_obj.save_classification == 2:
            return {'status': 1, 'msg': 'TL-OSS 存储暂未上线使用，敬请期待！'}  # TL-OSS存储
        else:
            native = f'{save_obj.save_path}/{fileName}'
            abs_path = f'{get_sys_url()}/apps/static{native}'
            dirName = os.path.dirname(abs_path)
            error = ''
            if not os.path.exists(dirName):
                try:
                    os.makedirs(dirName)
                except:
                    error = '创建目录失败!'
            elif not os.access(dirName, os.W_OK):
                error = '没有写入权限!'
            if error: return {"status": 1, "msg": error}
            with open(abs_path, 'wb')as fp:
                fp.write(file_data)
            return native  # 本地存储
    except:
        return None


@sys_bp.route('/upload', endpoint='upload', methods=['POST'])
@login_required
def upload_file():
    fileCls = ''
    image = ['gif', 'jpg', 'jpeg', 'png', 'bmp']
    flash = ['swf', 'flv']
    media = ['swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb']
    files = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2']
    dir = request.args.get('dir')
    if request.method == 'POST':
        file = request.files['imgFile']
        filename, fext = os.path.splitext(file.filename)
        rnd_name = '%s%s' % (get_uuid16(), fext)
        if dir == 'image':
            if fext.replace('.', '').lower() in image:
                fileCls = "images/"
        elif dir == 'flash':
            if fext.replace('.', '').lower() in flash:
                fileCls = "flash/"
        elif dir == 'media':
            if fext.replace('.', '').lower() in media:
                fileCls = "medias/"
        else:
            if fext.replace('.', '').lower() in files:
                fileCls = "files/"
        if fileCls:
            relative_path = os.path.join(fileCls, get_date_str(), rnd_name).replace('\\', '/')
            _path = qiNiu_upload(relative_path, file.read())
            if _path and isinstance(_path, str):
                return jsonify({"error": 0, "url": _path, 'message': '上传成功!'})
            elif _path and isinstance(_path, dict):
                return jsonify(_path)
            error = '上传异常,请确认存储配置正确!'
            return jsonify({"error": 1, "msg": error, 'message': error})
        return jsonify({"status": 1, "message": '上传失败,超出允许文件类型!'})
    return jsonify({"error": 1, "msg": "上传错误!", 'message': '上传错误!'})


@sys_bp.route('/upload_img', endpoint='upload_img', methods=['POST'])
@login_required
def upload():
    img_s = ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'ico']
    if request.method == 'POST':
        file = request.files['file']
        fname, fext = os.path.splitext(file.filename)
        rnd_name = '%s%s' % (get_uuid16(), fext.lower())
        if fext.replace('.', '').lower() in img_s:
            fileCls = "images/"
            relative_path = os.path.join(fileCls, get_date_str(), rnd_name).replace('\\', '/')
            if fext.replace('.', '').lower() in 'ico':
                save_obj = TL_Save_Model.query.first()
                native = f'{save_obj.save_path}/{relative_path}'
                abs_path = f'{get_sys_url()}/apps/static{native}'
                dirName = os.path.dirname(abs_path)
                error = ''
                if not os.path.exists(dirName):
                    try:
                        os.makedirs(dirName)
                    except:
                        error = '创建目录失败!'
                elif not os.access(dirName, os.W_OK):
                    error = '没有写入权限!'
                if error: return jsonify({"status": 1, "msg": error})
                file.save(abs_path)
                _path = native
            else:
                _path = qiNiu_upload(relative_path, file.read())
            if _path and isinstance(_path, str):
                return jsonify({"status": 0, "img_url": _path})
            elif _path and isinstance(_path, dict):
                return jsonify(_path)
            return jsonify({"status": 1, "msg": '上传异常,请确认存储配置正确'})
        return jsonify({"status": 1, "msg": '上传失败,超出允许文件类型!'})
    else:
        return jsonify({"status": 1, "msg": '未知请求错误'})
